/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.common.utility;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.fasterxml.jackson.databind.JsonNode;

import java.util.function.Consumer;

/**
 * JsonNode function   utility
 *
 * @author guozhiqi
 */
public class JsonNodeUtility {
    /**
     * 递归查找contents节点下的对应节点内容
     *
     * @param jsonArray
     * @param functionAction
     */
    public static void rescureContents(JSONArray jsonArray, Consumer<JSONObject> functionAction) {
        rescureWithSpecificTag(jsonArray, "contents", functionAction);
    }

    /**
     * 依据子节点标识进行递归
     *
     * @param jsonArray
     * @param functionAction
     */
    public static void rescureWithSpecificTag(JSONArray jsonArray, String childTag, Consumer<JSONObject> functionAction) {
        if (jsonArray == null || jsonArray.size() == 0) {
            return;
        }
        if (StringUtility.isNullOrEmpty(childTag)) {
            childTag = "contents";
        }
        String finalChildTag = childTag;
        jsonArray.forEach(jsonItem -> {
            if (jsonItem instanceof JSONArray) {
                JSONArray itemJsonArray = (JSONArray) jsonItem;
                rescureContents(itemJsonArray, functionAction);
            } else if (jsonItem instanceof JSONObject) {
                JSONObject jsonObjectItem = (JSONObject) jsonItem;

                // 执行回调
                functionAction.accept(jsonObjectItem);

                if (jsonObjectItem.get(finalChildTag) instanceof JSONArray) {
                    JSONArray contentsJsonArray = (JSONArray) jsonObjectItem.get(finalChildTag);
                    rescureContents(contentsJsonArray, functionAction);
                }
            }
        });
    }

    /**
     * 查找指定属性名称
     * @param sourceNode
     * @param attributeName
     * @return
     */
    public static JSONArray findAll(JsonNode sourceNode, String attributeName) {
        if (sourceNode == null || StringUtility.isNullOrEmpty(attributeName)) {
            return new JSONArray();
        }

        return (JSONArray) JSONPath.extract(sourceNode.toString(), "$.." + attributeName);
    }
}
